package com.sunxboy.platform.service;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class EmailClientServiceImpl {

    private final String host;
    private final String from;
    private final String to;
    private final String subjectprefix;

    public EmailClientServiceImpl(final Map<String, String> emailConfigMap) {
        this.host = emailConfigMap.get("HOST");
        this.from = emailConfigMap.get("FROM");
        this.to = emailConfigMap.get("TO");
        this.subjectprefix = emailConfigMap.get("SUBJECTPREFIX");
    }

    public boolean sendEmail(final String emailContent, final List<String> attachmentFiles) {

        boolean retVal = true;
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);

        try {
            MimeMessagePreparator mimepreparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setTo(to);
                    message.setFrom(from);
                    // java.net.InetAddress localMachine =
                    // java.net.InetAddress.getLocalHost();
                    message.setSubject(subjectprefix);
                    message.setText(emailContent);
                    if (attachmentFiles != null) {
                        for (String file : attachmentFiles) {
                            File attachmentFile = new File(file);
                            if (attachmentFile.exists() && attachmentFile.isFile()) {
                                message.addAttachment(attachmentFile.getName(), attachmentFile);
                            }
                        }
                    }
                }
            };
            mailSender.send(mimepreparator);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            retVal = false;
        }
        return retVal;
    }
}
